<template>
  <div class="log-cache-monitor">
    <el-card class="header-card">
      <template #header>
        <div class="card-header">
          <span class="title">
            <el-icon><DataBoard /></el-icon>
            网络日志接收监控
          </span>
          <el-button
            type="primary"
            size="small"
            @click="refreshData"
            :loading="loading"
          >
            <el-icon><Refresh /></el-icon>
            刷新
          </el-button>
        </div>
      </template>

      <el-alert
        title="日志存储说明"
        type="info"
        :closable="false"
        show-icon
      >
        <p>📝 日志采集流程：接收日志 → Redis缓存 → 定时回写MySQL</p>
        <p>⏰ 自动回写：每12小时（00:00和12:00）自动执行</p>
        <p>🚀 Redis缓存保证高性能写入，异步回写保证数据持久化</p>
      </el-alert>
    </el-card>

    <!-- 统计卡片 -->
    <el-row :gutter="20" style="margin-top: 20px">
      <el-col :xs="24" :sm="12" :md="6">
        <el-card class="stat-card">
          <el-statistic title="Redis缓存日志总数" :value="stats.totalCachedCount || 0">
            <template #prefix>
              <el-icon color="#409eff"><Document /></el-icon>
            </template>
          </el-statistic>
        </el-card>
      </el-col>

      <el-col :xs="24" :sm="12" :md="6">
        <el-card class="stat-card">
          <el-statistic title="待回写日期分组" :value="stats.pendingDateCount || 0">
            <template #prefix>
              <el-icon color="#67c23a"><Calendar /></el-icon>
            </template>
          </el-statistic>
        </el-card>
      </el-col>

      <el-col :xs="24" :sm="12" :md="6">
        <el-card class="stat-card">
          <div class="status-item">
            <div class="status-label">回写任务状态</div>
            <el-tag
              :type="stats.isWriteBackRunning ? 'warning' : 'success'"
              size="large"
              effect="dark"
            >
              {{ stats.isWriteBackRunning ? '执行中...' : '空闲' }}
            </el-tag>
          </div>
        </el-card>
      </el-col>

      <el-col :xs="24" :sm="12" :md="6">
        <el-card class="stat-card">
          <el-button
            type="primary"
            @click="handleManualWriteBack"
            :loading="writeBackLoading"
            :disabled="stats.isWriteBackRunning"
            style="width: 100%; height: 60px"
          >
            <el-icon><Upload /></el-icon>
            手动触发回写
          </el-button>
        </el-card>
      </el-col>
    </el-row>

    <!-- 日期详情表格 -->
    <el-card style="margin-top: 20px">
      <template #header>
        <div class="card-header">
          <span class="title">
            <el-icon><List /></el-icon>
            各日期缓存详情
          </span>
          <el-tag type="info" v-if="dateTableData.length > 0">
            共 {{ totalDates }} 个日期
          </el-tag>
        </div>
      </template>

      <el-table
        :data="paginatedTableData"
        border
        stripe
        v-loading="loading"
      >
        <el-table-column type="index" label="序号" width="80" align="center" />
        <el-table-column prop="date" label="日期" width="180" align="center">
          <template #default="{ row }">
            <el-tag type="primary" effect="plain">
              {{ row.date }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="count" label="缓存日志数量" align="center">
          <template #default="{ row }">
            <el-tag type="info" size="large">
              {{ row.count.toLocaleString() }} 条
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="占比" width="150" align="center">
          <template #default="{ row }">
            <el-progress
              :percentage="getPercentage(row.count)"
              :stroke-width="16"
              :color="getProgressColor(row.count)"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" align="center">
          <template #default="{ row }">
            <el-button
              type="danger"
              size="small"
              @click="handleDelete(row.date)"
              :disabled="stats.isWriteBackRunning"
            >
              <el-icon><Delete /></el-icon>
              删除缓存
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-empty
        v-if="dateTableData.length === 0 && !loading"
        description="当前没有缓存数据"
      />

      <!-- 分页组件 -->
      <div class="pagination-container" v-if="dateTableData.length > 0">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[5, 10, 20, 50]"
          :total="totalDates"
          layout="total, sizes, prev, pager, next, jumper"
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, onUnmounted } from 'vue'
import { ElMessage, ElMessageBox, ElNotification, ElLoading } from 'element-plus'
import {
  DataBoard,
  Refresh,
  Document,
  Calendar,
  Upload,
  List,
  Delete
} from '@element-plus/icons-vue'
import * as logCacheApi from '@/api/logCache'

// 数据
const loading = ref(false)
const writeBackLoading = ref(false)
const stats = reactive({
  totalCachedCount: 0,
  pendingDateCount: 0,
  isWriteBackRunning: false,
  pendingDates: [],
  dateLogCounts: {}
})
const dateTableData = ref([])
let autoRefreshTimer = null

// 分页数据
const currentPage = ref(1)
const pageSize = ref(10)

// 计算属性
const totalDates = computed(() => dateTableData.value.length)

// 分页后的数据
const paginatedTableData = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return dateTableData.value.slice(start, end)
})

// 加载数据
const loadData = async () => {
  loading.value = true
  try {
    const res = await logCacheApi.getCacheStats()
    if (res.code === 200) {
      Object.assign(stats, res.data)
      
      // 构建表格数据
      if (stats.dateLogCounts) {
        dateTableData.value = Object.entries(stats.dateLogCounts).map(([date, count]) => ({
          date,
          count
        })).sort((a, b) => b.date.localeCompare(a.date))
      }
    }
  } catch (error) {
    ElMessage.error('加载数据失败')
  } finally {
    loading.value = false
  }
}

// 刷新数据
const refreshData = () => {
  loadData()
}

// 手动触发回写
const handleManualWriteBack = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要手动触发回写任务吗？这将把Redis中的日志批量写入MySQL。',
      '确认操作',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    // 显示加载提示
    const loadingInstance = ElLoading.service({
      lock: true,
      text: '正在执行回写任务，请稍候...',
      background: 'rgba(0, 0, 0, 0.7)'
    })

    try {
      writeBackLoading.value = true
      const res = await logCacheApi.triggerWriteBack()
      
      loadingInstance.close()

      if (res.code === 200) {
        // 等待任务执行完成
        await checkWriteBackStatus()
      } else {
        ElMessage.error({
          message: res.message || '触发回写失败',
          duration: 5000,
          showClose: true
        })
      }
    } catch (error) {
      loadingInstance.close()
      ElMessage.error({
        message: '回写任务执行失败：' + (error.message || '未知错误'),
        duration: 5000,
        showClose: true
      })
    } finally {
      writeBackLoading.value = false
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('触发回写失败')
    }
  }
}

// 检查回写状态
const checkWriteBackStatus = async () => {
  let checkCount = 0
  const maxChecks = 30 // 最多检查30次（30秒）
  
  const checkInterval = setInterval(async () => {
    try {
      const statusRes = await logCacheApi.getWriteBackStatus()
      checkCount++

      if (statusRes.code === 200) {
        const status = statusRes.data
        
        // 任务执行完成
        if (!status.isRunning) {
          clearInterval(checkInterval)
          
          // 刷新数据
          await loadData()
          
          // 显示结果（从lastResult中获取详细数据）
          const lastResult = status.lastResult
          if (lastResult) {
            const totalSuccess = lastResult.totalSuccess || 0
            const totalFailed = lastResult.totalFailed || 0
            const totalProcessed = lastResult.totalProcessed || 0
            
            if (lastResult.error) {
              ElNotification({
                title: '回写失败 ❌',
                message: `回写任务执行失败：${lastResult.error}`,
                type: 'error',
                duration: 8000
              })
            } else if (totalFailed === 0 && totalSuccess > 0) {
              ElNotification({
                title: '回写成功 ✅',
                message: `成功写入 ${totalSuccess} 条日志到MySQL数据库`,
                type: 'success',
                duration: 5000
              })
            } else if (totalFailed > 0) {
              ElNotification({
                title: '回写部分失败 ⚠️',
                message: `成功：${totalSuccess} 条，失败：${totalFailed} 条。请检查后端日志查看详细错误信息。`,
                type: 'warning',
                duration: 8000
              })
            } else if (totalProcessed === 0) {
              ElMessage.info('回写任务完成，但没有数据需要处理')
            }
          } else {
            ElMessage.success('回写任务完成')
          }
          return
        }
      }

      // 超时处理
      if (checkCount >= maxChecks) {
        clearInterval(checkInterval)
        ElMessage.warning('回写任务执行时间较长，请稍后手动刷新查看结果')
        await loadData()
      }
    } catch (error) {
      clearInterval(checkInterval)
      ElMessage.error('检查回写状态失败')
      await loadData()
    }
  }, 1000) // 每秒检查一次
}

// 删除缓存
const handleDelete = async (date) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除 ${date} 的缓存数据吗？删除后无法恢复！`,
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    const res = await logCacheApi.deleteCachedLogs(date)
    if (res.code === 200) {
      ElMessage.success('删除成功')
      // 如果删除后当前页没有数据，回到上一页
      if (paginatedTableData.value.length === 1 && currentPage.value > 1) {
        currentPage.value--
      }
      loadData()
    } else {
      ElMessage.error(res.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 分页事件处理
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
}

const handleCurrentChange = (val) => {
  currentPage.value = val
}

// 计算百分比
const getPercentage = (count) => {
  if (stats.totalCachedCount === 0) return 0
  const percentage = (count / stats.totalCachedCount) * 100
  return Math.round(percentage * 100) / 100
}

// 进度条颜色
const getProgressColor = (count) => {
  const percentage = getPercentage(count)
  if (percentage < 20) return '#67c23a'
  if (percentage < 50) return '#409eff'
  if (percentage < 80) return '#e6a23c'
  return '#f56c6c'
}

// 生命周期
onMounted(() => {
  loadData()
  
  // 每30秒自动刷新
  autoRefreshTimer = setInterval(() => {
    loadData()
  }, 30000)
})

onUnmounted(() => {
  if (autoRefreshTimer) {
    clearInterval(autoRefreshTimer)
  }
})
</script>

<style scoped lang="scss">
.log-cache-monitor {
  padding: 20px;

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .title {
      display: flex;
      align-items: center;
      gap: 8px;
      font-size: 16px;
      font-weight: bold;
    }
  }

  .header-card {
    :deep(.el-alert) {
      p {
        margin: 5px 0;
        line-height: 1.8;
      }
    }
  }

  .stat-card {
    height: 100%;
    min-height: 120px;
    display: flex;
    align-items: center;
    justify-content: center;

    .status-item {
      text-align: center;

      .status-label {
        font-size: 14px;
        color: #909399;
        margin-bottom: 10px;
      }
    }

    :deep(.el-statistic) {
      .el-statistic__head {
        font-size: 14px;
        color: #909399;
        margin-bottom: 10px;
      }

      .el-statistic__content {
        font-size: 28px;
        font-weight: bold;
      }
    }
  }

  .pagination-container {
    display: flex;
    justify-content: center;
    margin-top: 20px;
    padding: 10px 0;
  }
}
</style>

